<template>
  <div class="w-100">
    <Select
      v-model="companyName"
      filterable
      :remote-method="remoteMethod"
      clearable
      :loading="loading"
      :placeholder="placeholder"
      :disabled="disabled"
      @on-select="onSelect"
      @on-clear="onClear"
    >
      <Option v-for="(it, index) in options" :value="it.companyName" :key="index">{{it.companyName}}</Option>
    </Select>
  </div>
</template>

<script>
import { debounce } from 'lodash';
import { getCompanySelectByCompanyName } from "@/api/system.js";

export default {
  name: 'companySelect',
  model: {
    prop: "value",
    event: "input",
  },
  props: {
    // 地址
    value: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请输入公司名称'
    },
  },
  watch: {
    value: {
      // immediate: true,
      handler (val) {
        this.companyName = val
      }
    },
  },
  data () {
    return {
      companyName: '',
      loading: false,
      options: [],
    }
  },
  methods: {
    remoteMethod: debounce(async function (companyName) {
      if (companyName) {
        this.loading = true;
        const data = await getCompanySelectByCompanyName({ companyName });
        this.options = data
        this.loading = false;
      } else {
        this.options = [];
      }
    }, 500),
    onSelect (item) {
      const companyId = this.options.find(it => it.companyName === item.label).companyId

      this.$emit('input', item.value)
      this.$emit('getData', companyId)
    },
    onClear () {
      this.$emit('getData', '')
    }
  }
}
</script>

<style lang='less' scoped>
.w-100 {
  width: 100%;
}
</style>
